package com.jfl.service.impl.system;

import java.util.List;

import org.apache.curator.shaded.com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Service;
import com.jfl.base.BaseServiceImpl;
import com.jfl.common.MessageKey;
import com.jfl.config.Resources;
import com.jfl.exception.BusinessException;
import com.jfl.mapper.SysPostMapper;
import com.jfl.mapper.SysUserPostMapper;
import com.jfl.model.SysPost;
import com.jfl.system.SysPostService;
import com.jfl.utils.ConvertUtil;
/**
 * 岗位管理
 *  
 * @author  赵炎
 * @version  [V1.00, 2018年12月20日]
 * @since V1.00
 */
@Component
@Service(version="${jfl.version}")
public class SysPostServiceImpl extends BaseServiceImpl<SysPost, SysPostMapper> implements SysPostService
{
    @Autowired
    private SysUserPostMapper sysUserPostMapper;
    
    @Override
    public List<SysPost> selectPostsByUserId(Long userId)
    {
        List<Long> userPosts = this.mapper.selectPostsByUserId(userId);
        List<SysPost> posts = this.mapper.selectByMap(Maps.newHashMap());
        for (SysPost sysPost : posts)
        {
            if (userPosts.contains(sysPost.getId()))
            {
                sysPost.setFlag(Boolean.TRUE);
            }
        }
        return posts;
    }

    @Override
    public String checkPostNameUnique(SysPost post)
    {
        Long id = post.getId() == null ? -1L : post.getId();
        SysPost record = this.mapper.selectByPostName(post.getPostName());
        return result(record, id);
    }

    @Override
    public String checkPostCodeUnique(SysPost post)
    {
        Long id = post.getId() == null ? -1L : post.getId();
        SysPost record = this.mapper.selectByPostCode(post.getPostCode());
        return result(record, id);
    }

    @Transactional
    @Override
    public void deleteByIds(String ids)throws BusinessException
    {
        Long[] arr = ConvertUtil.toLongArray(ids);
        for (Long id : arr)
        {
            SysPost post = queryById(id);
            if(post != null)
            {
                int count = this.sysUserPostMapper.countByPostId(id);
                if (count > 0)
                {
                    throw new BusinessException(String.format(Resources.getMessage(MessageKey.MESSAGE_FORMAT), post.getPostName()));
                }
                this.mapper.deleteById(id);
            }
        }
        
    }

}
